//
//  BIDOutingReportViewController.m
//  cxgov
//
//  Created by mal on 16/3/14.
//  Copyright © 2016年 mal. All rights reserved.
//

#import "BIDCreateOutingReportViewController.h"
#import "BIDCustomTextField.h"
#import "BIDCustomTextView.h"
#import "BIDMemberListViewController.h"
#import "BIDCustomDateView.h"

#import "BIDOutingReportWithTextFieldCell.h"
#import "BIDOutingReportWithTextViewCell.h"
#import "UIView+FindFirstResponder.h"

//新增外出报备
static NSString *createOutingReportURL = @"outingAndroid!addOuting.action";

@interface BIDCreateOutingReportViewController ()<BIDMemberListViewControllerDelegate, BIDCustomDateViewDelegate, UITextFieldDelegate, UIAlertViewDelegate, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>
{
    BOOL _bCC;
    NSString *_toMemberIds;
    NSString *_ccIds;
    BIDCustomDateView *_dateView;
    NSString *_selectDate;
    //获取焦点的编辑框的位置
    CGRect _desRect;
    //
    NSMutableArray *_dataSourceArr;
    BOOL _isRegister;
    UITextField *_curTF;
}
@end

@implementation BIDCreateOutingReportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加报备";
    _selectDate = @"";
    _toMemberIds = @"";
    _ccIds = @"";
    // Do any additional setup after loading the view from its nib.
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //
    _dateView = [[BIDCustomDateView alloc] initWithMode:3];
    _dateView.bIsInputView = YES;
    _dateView.delegate = self;
    //
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(submitBtnHandler)];
    //
    [self prepareData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)prepareData
{
    NSArray *tempArr = nil;
    tempArr = @[@[@{@"title":@"主送人", @"content":@"", @"value":@"", @"placeholder":@"请选择主送人", @"keyboardType":@"person", @"ctrlType":@"textField", @"field":@"receiveId"},
                  @{@"title":@"抄送人", @"content":@"", @"value":@"", @"placeholder":@"请选择抄送人", @"keyboardType":@"person", @"ctrlType":@"textField", @"field":@"ccId"},
                  @{@"title":@"出发日期", @"content":@"", @"value":@"", @"placeholder":@"设置出发日期", @"keyboardType":@"time", @"ctrlType":@"textField", @"field":@"outing.startTime"},
                  @{@"title":@"返回日期", @"content":@"", @"value":@"", @"placeholder":@"设置返回日期", @"keyboardType":@"time", @"ctrlType":@"textField", @"field":@"outing.endTime"},
                  @{@"title":@"外出地点", @"content":@"", @"value":@"", @"placeholder":@"请填写您的外出地点", @"keyboardType":@"normal", @"ctrlType":@"textField", @"field":@"outing.address"},
                  @{@"title":@"外出事由", @"content":@"", @"value":@"", @"placeholder":@"请填写您的外出事由", @"keyboardType":@"normal", @"ctrlType":@"textView", @"field":@"outing.reason"}],
                @[@{@"title":@"姓名", @"content":@"", @"value":@"", @"placeholder":@"填写主持工作同志姓名", @"keyboardType":@"normal", @"ctrlType":@"textField", @"field":@"outing.agentName"},
                  @{@"title":@"职务", @"content":@"", @"value":@"", @"placeholder":@"填写主持工作同志职务", @"keyboardType":@"normal", @"ctrlType":@"textField", @"field":@"outing.agentPosition"},
                  @{@"title":@"办公电话", @"content":@"", @"value":@"", @"placeholder":@"填写主持工作同志办公电话", @"keyboardType":@"phone", @"ctrlType":@"textField", @"field":@"outing.cphone"},
                  @{@"title":@"移动电话", @"content":@"", @"value":@"", @"placeholder":@"填写主持工作同志移动电话", @"keyboardType":@"phone", @"ctrlType":@"textField", @"field":@"outing.mphone"},
                  @{@"title":@"备注", @"content":@"", @"value":@"", @"placeholder":@"填写备注信息", @"keyboardType":@"normal", @"ctrlType":@"textView", @"field":@"outing.agentRemark"}]];
    _dataSourceArr = [[NSMutableArray alloc] initWithArray:tempArr];
}
//提交报备
- (void)submitBtnHandler
{
    for(NSUInteger i=0; i<_dataSourceArr.count; i++)
    {
        NSArray *arr = _dataSourceArr[i];
        for(NSUInteger j=0; j<arr.count; j++)
        {
            NSDictionary *dic = arr[j];
            NSString *strContent = ANY2NSSTRING(dic[@"content"]);
            if(strContent.length == 0)
            {
                NSString *strMsg = [[NSString alloc] initWithFormat:@"%@不能为空", dic[@"title"]];
                [self showAlertView:strMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
                return;
            }
        }
    }
    //
    NSString *strRequestURL = @"";
    strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], createOutingReportURL];
    NSMutableString *strPost = [NSMutableString string];
    [strPost appendFormat:@"outing.createUser=%@", [AppDelegate getUserId]];
    for(NSUInteger i=0; i<_dataSourceArr.count; i++)
    {
        NSArray *arr = _dataSourceArr[i];
        for(NSUInteger j=0; j<arr.count; j++)
        {
            NSDictionary *dic = arr[j];
            [strPost appendFormat:@"&%@=%@", dic[@"field"], dic[@"value"]];
        }
    }
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showAlertView:@"发布成功" buttonTitle:ALERT_BTN_TITLE tag:@100 functionName:@"alertViewHandler:"];
        }
    }];
}

- (void)alertViewHandler:(id)obj
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 键盘显示与隐藏
 
 @param notification <#notification description#>
 */
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    self.keyboardHeight = keyboardSize.height;
    NSLog(@"keyboardHeight=%f", self.keyboardHeight);
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.25f];
    UIView *tempView = [self.view findFirstResponder];
    //if([tempView isKindOfClass:[UITextField class]])
    {
        if(_desRect.origin.y+_desRect.size.height > CGRectGetHeight(self.view.frame)-self.keyboardHeight)
        {
            self.distanceToMove = _desRect.origin.y+_desRect.size.height-(CGRectGetHeight(self.view.frame)-self.keyboardHeight);
            CGPoint pt = _tableView.contentOffset;
            pt.y += self.distanceToMove;
            [_tableView setContentOffset:pt animated:YES];
        }
    }
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.30f];
    CGPoint pt = _tableView.contentOffset;
    if(pt.y-self.distanceToMove < 0)
    {
        pt.y = 0;
    }
    else
    {
        pt.y -= self.distanceToMove;
    }
    [_tableView setContentOffset:pt animated:YES];
    [UIView commitAnimations];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 1)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _curTF = textField;
    NSUInteger tag = textField.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;
    NSDictionary *dic = _dataSourceArr[section][row];
    if([dic[@"keyboardType"] isEqualToString:@"person"])
    {
        [textField resignFirstResponder];
        BIDMemberListViewController *vc = [[BIDMemberListViewController alloc] init];
        vc.delegate = self;
        vc.chooseType = TYPE_CHECK;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
        CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
        CGRect rect = [_tableView convertRect:rectInTableView toView:[_tableView superview]];
        _desRect = rect;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSUInteger tag = textField.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[section][row]];
    [dic setObject:textField.text forKey:@"value"];
    [dic setObject:textField.text forKey:@"content"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    [tempArr replaceObjectAtIndex:row withObject:dic];
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    NSUInteger tag = textView.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    CGRect rectInTableView = [_tableView rectForRowAtIndexPath:indexPath];
    CGRect rect = [_tableView convertRect:rectInTableView toView:[_tableView superview]];
    _desRect = rect;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    NSUInteger tag = textView.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[section][row]];
    [dic setObject:textView.text forKey:@"value"];
    [dic setObject:textView.text forKey:@"content"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    [tempArr replaceObjectAtIndex:row withObject:dic];
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
}

#pragma mark - BIDCustomDateViewDelegate
- (void)getDate:(NSString *)strDate
{
    _curTF.text = strDate;
    NSUInteger tag = _curTF.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[section][row]];
    [dic setObject:strDate forKey:@"value"];
    [dic setObject:strDate forKey:@"content"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    [tempArr replaceObjectAtIndex:row withObject:dic];
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
}

#pragma mark - BIDMemberListViewControllerDelegate
- (void)getChoosedMember:(NSString *)ids andNames:(NSString *)names
{
    NSUInteger tag = _curTF.tag;
    NSUInteger section = tag/30;
    NSUInteger row = tag%30;
    NSString *str = @"";
    NSArray *arr = [names componentsSeparatedByString:@","];
    if(arr && arr.count>5)
    {
        str = [[NSString alloc] initWithFormat:@"%@,%@等%ld人", arr[0], arr[1], arr.count];
    }
    else if(arr)
    {
        str = names;
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:_dataSourceArr[section][row]];
    [dic setObject:ids forKey:@"value"];
    [dic setObject:str forKey:@"content"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:_dataSourceArr[section]];
    [tempArr replaceObjectAtIndex:row withObject:dic];
    [_dataSourceArr replaceObjectAtIndex:section withObject:tempArr];
    [_tableView reloadData];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSourceArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataSourceArr[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier1 = @"withTextField";
    static NSString *identifier2 = @"withTextView";
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    if(!_isRegister)
    {
        _isRegister = YES;
        UINib *nib1 = [UINib nibWithNibName:@"BIDOutingReportWithTextFieldCell" bundle:nil];
        [tableView registerNib:nib1 forCellReuseIdentifier:identifier1];
        UINib *nib2 = [UINib nibWithNibName:@"BIDOutingReportWithTextViewCell" bundle:nil];
        [tableView registerNib:nib2 forCellReuseIdentifier:identifier2];
    }
    NSDictionary *dic = _dataSourceArr[section][row];
    if([dic[@"ctrlType"] isEqualToString:@"textField"])
    {
        BIDOutingReportWithTextFieldCell *withTextFieldCell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        withTextFieldCell.titleLabel.text = dic[@"title"];
        withTextFieldCell.contentTF.text = dic[@"content"];
        withTextFieldCell.contentTF.delegate = self;
        withTextFieldCell.contentTF.placeholder = dic[@"placeholder"];
        withTextFieldCell.contentTF.rightView = nil;
        withTextFieldCell.contentTF.tag = section*30+row;
        if([dic[@"keyboardType"] isEqualToString:@"normal"])
        {
            withTextFieldCell.contentTF.keyboardType = UIKeyboardTypeDefault;
            withTextFieldCell.contentTF.inputView = nil;
            withTextFieldCell.contentTF.inputAccessoryView = self.toolBar;
        }
        else if([dic[@"keyboardType"] isEqualToString:@"phone"])
        {
            withTextFieldCell.contentTF.keyboardType = UIKeyboardTypePhonePad;
            withTextFieldCell.contentTF.inputView = nil;
            withTextFieldCell.contentTF.inputAccessoryView = self.toolBar;
        }
        else if([dic[@"keyboardType"] isEqualToString:@"person"])
        {
            UIImageView *imgView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"avatar.png"]];
            withTextFieldCell.contentTF.rightView = imgView2;
            withTextFieldCell.contentTF.rightViewMode = UITextFieldViewModeAlways;
        }
        else if([dic[@"keyboardType"] isEqualToString:@"time"])
        {
            withTextFieldCell.contentTF.inputView = _dateView;
            withTextFieldCell.contentTF.inputAccessoryView = nil;
        }
        cell = withTextFieldCell;
    }
    else
    {
        BIDOutingReportWithTextViewCell *withTextViewCell = [tableView dequeueReusableCellWithIdentifier:identifier2];
        withTextViewCell.titleLabel.text = dic[@"title"];
        withTextViewCell.contentTextView.text = dic[@"content"];
        withTextViewCell.contentTextView.inputAccessoryView = self.toolBar;
        withTextViewCell.contentTextView.placeholder = dic[@"placeholder"];
        withTextViewCell.contentTextView.delegate = self;
        withTextViewCell.contentTextView.tag = section * 30 + row;
        cell = withTextViewCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = _dataSourceArr[indexPath.section][indexPath.row];
    if([dic[@"ctrlType"] isEqualToString:@"textField"])
    {
        return 79.f;
    }
    else
    {
        return 132.f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 44)];
    [headerView setBackgroundColor:[UIColor whiteColor]];
    //
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(headerView.frame), 1)];
    [lineLabel setBackgroundColor:[UIColor lightGrayColor]];
    [headerView addSubview:lineLabel];
    //
    CGFloat labelWidth = 200;
    CGFloat labelHeight = CGRectGetHeight(headerView.frame);
    CGFloat posX = (CGRectGetWidth(headerView.frame)-labelWidth)/2;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(posX, 0, labelWidth, labelHeight)];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setTextColor:SHIMO_COLOR];
    [label setFont:[UIFont systemFontOfSize:15.f]];
    [label setText:@"代其主持工作同志"];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 0;
    else return 44.f;
}

@end
